import java.util.LinkedList ;
import javax.swing.* ;
import java.awt.*;

public class ParameterWindow {
	private IParameters obj ;
	private String [ ] name = null ;
	private JTextField [ ] data = null ;

	public ParameterWindow ( IParameters obj ) {
		this.obj = obj ;
	}
	
	public JPanel getPanel ( ) {
		JPanel p = new JPanel ( ) ;
		GridBagLayout layout = new GridBagLayout ( ) ;
		GridBagConstraints c = new GridBagConstraints ( ) ;
		LinkedList<ParameterData> params = obj.getParams ( ) ;
		int numParams = params.size ( ) ;
		JLabel label ;
		int i ;
	
		p.setLayout ( layout ) ;
		c.anchor = GridBagConstraints.EAST ;
		name = new String [ numParams ] ;
		data = new JTextField [ numParams ] ;
		i = 0 ;
		for ( ParameterData param : params ) {
			c.gridwidth = GridBagConstraints.RELATIVE ;
			c.fill = GridBagConstraints.NONE ;
			c.weightx = 0 ;
			name [ i ] = param.name ;
			label = new JLabel ( param.name + " " ) ;
			p.add ( label  , c ) ;

			c.gridwidth = GridBagConstraints.REMAINDER ;
			c.fill = GridBagConstraints.HORIZONTAL ;
			c.weightx = 1 ;
			data [ i ] = new JTextField ( param.data , 13 ) ;
			p.add ( data [ i ] , c ) ;

			i ++ ;
		}
		return p ;
	
	}
	
	public void commit ( ) {
		int i ;
		
		try {
			for ( i = 0 ; i < name.length ; i ++ ) {
				obj.setParam ( name [ i ] , data[i].getText ( ) ) ;

				// set the displayed value to the one just stored
				// necessary in case of an invalid entry
				data[i].setText ( obj.getParam ( name [ i ] ) ) ;			
			}
		} catch ( Exception e ) {
		}
	}
	
	public static void configure ( IParameters obj ) {
		configure ( obj , "Select Parameters" ) ;
	}
	
	public static void configure ( IParameters obj , String title ) {
		int choice , i ;
		LinkedList<ParameterData> params = obj.getParams ( ) ;
		GridBagLayout layout = new GridBagLayout ( ) ;
		GridBagConstraints c = new GridBagConstraints ( ) ;
		int numParams = params.size ( ) ;
		String [ ] name = new String [ numParams ] ;
		JTextField [ ] data = new JTextField [ numParams ] ;
		JLabel label ;
		JPanel p ;

		do {
			p = new JPanel ( ) ;
			p.setLayout ( layout ) ;
			c.anchor = GridBagConstraints.EAST ;
			i = 0 ;
			for ( ParameterData param : params ) {
				c.gridwidth = GridBagConstraints.RELATIVE ;
				c.fill = GridBagConstraints.NONE ;
				c.weightx = 0 ;
				name [ i ] = param.name ;
				label = new JLabel ( param.name + " " ) ;
				p.add ( label  , c ) ;

				c.gridwidth = GridBagConstraints.REMAINDER ;
				c.fill = GridBagConstraints.HORIZONTAL ;
				c.weightx = 1 ;
				data [ i ] = new JTextField ( param.data , 13 ) ;
				p.add ( data [ i ] , c ) ;

				i ++ ;
			}
		
			choice = JOptionPane.showConfirmDialog ( null , p , title , JOptionPane.OK_CANCEL_OPTION , JOptionPane.PLAIN_MESSAGE ) ;
		} while ( choice != JOptionPane.OK_OPTION ) ;

		for ( i = 0 ; i < numParams ; i ++ ) {
			obj.setParam ( name [ i ] , data[i].getText ( ) ) ;
		}
	}
}
